// pkg/integration/full_service.go
// 完整服务集成示例

package integration

import (
	"context"
	"fmt"
	"log"
	"net"
	"net/http"
	"sync"
	"time"

	"github.com/onyx/snapshotter/pkg/cache"
	"github.com/onyx/snapshotter/pkg/config"
	"github.com/onyx/snapshotter/pkg/dedup"
	"github.com/onyx/snapshotter/pkg/fanotify"
	"github.com/onyx/snapshotter/pkg/metadata"
	"github.com/onyx/snapshotter/pkg/prefetch"
	"github.com/onyx/snapshotter/pkg/registry"
	"github.com/onyx/snapshotter/pkg/service"
	"github.com/onyx/snapshotter/pkg/stats"
	"github.com/onyx/snapshotter/pkg/ublk"
	"google.golang.org/grpc"
)

// FullService 完整的 onyx 服务
type FullService struct {
	config      *config.Config
	snapshotter *service.Snapshotter
	downloader  *fanotify.Downloader
	prefetcher  *prefetch.Service
	collector   *stats.Collector
	httpServer  *http.Server

	mu sync.Mutex
}

// NewFullService 创建完整服务
func NewFullService(cfg *config.Config) (*FullService, error) {
	// 初始化 Snapshotter
	snapshotter, err := service.NewSnapshotter(cfg)
	if err != nil {
		return nil, fmt.Errorf("failed to create snapshotter: %w", err)
	}

	// 初始化下载器
	downloader := fanotify.NewDownloader(4)

	// 初始化预取器
	registryClient := registry.NewClient()
	prefetcher := prefetch.NewService(2, &registryDownloader{client: registryClient})

	// 初始化统计收集器
	collector := stats.NewCollector(1000)

	fs := &FullService{
		config:      cfg,
		snapshotter: snapshotter,
		downloader:  downloader,
		prefetcher:  prefetcher,
		collector:   collector,
	}

	return fs, nil
}

// Start 启动服务
func (fs *FullService) Start(ctx context.Context) error {
	// 启动下载器
	fs.downloader.Start(ctx)

	// 启动预取服务
	fs.prefetcher.Start(ctx)

	// 启动统计 HTTP 服务
	if err := fs.startStatsServer(); err != nil {
		return fmt.Errorf("failed to start stats server: %w", err)
	}

	log.Println("Full service started successfully")
	return nil
}

// startStatsServer 启动统计 HTTP 服务
func (fs *FullService) startStatsServer() error {
	handler := stats.NewStatsHandler(fs.collector)
	fs.httpServer = &http.Server{
		Addr:    ":8080",
		Handler: handler,
	}

	go func() {
		if err := fs.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Printf("Stats server error: %v", err)
		}
	}()

	log.Println("Stats server started on :8080")
	return nil
}

// PullImage 拉取镜像（集成示例）
func (fs *FullService) PullImage(ctx context.Context, imageRef string, lazy bool) error {
	log.Printf("Pulling image: %s (lazy=%v)", imageRef, lazy)

	// 创建拉取器
	puller := registry.NewPuller("/tmp/onyx-pull-cache")
	defer puller.Close()

	// 拉取镜像
	layerPaths, err := puller.PullImage(ctx, imageRef, lazy)
	if err != nil {
		return fmt.Errorf("failed to pull image: %w", err)
	}

	// 注册层到 snapshotter
	for i, layerPath := range layerPaths {
		key := fmt.Sprintf("layer-%d", i)
		if err := fs.registerLayer(ctx, key, layerPath); err != nil {
			log.Printf("Warning: failed to register layer %s: %v", key, err)
		}
	}

	log.Println("Image pulled successfully")
	return nil
}

// registerLayer 注册层
func (fs *FullService) registerLayer(ctx context.Context, key string, layerPath string) error {
	// 对层进行去重处理
	mounts := []string{layerPath}

	// 这里应该调用 snapshotter 的相关方法
	// 简化起见，仅记录日志
	log.Printf("Registered layer %s from %s", key, layerPath)

	// 记录下载统计
	fs.collector.RecordDownload(100 * 1024 * 1024) // 假设 100MB

	return nil
}

// Stop 停止服务
func (fs *FullService) Stop(ctx context.Context) error {
	fs.mu.Lock()
	defer fs.mu.Unlock()

	// 停止预取服务
	fs.prefetcher.Stop()

	// 停止下载器
	fs.downloader.Stop()

	// 关闭 HTTP 服务器
	if fs.httpServer != nil {
		shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		fs.httpServer.Shutdown(shutdownCtx)
	}

	// 关闭 snapshotter
	fs.snapshotter.Close()

	log.Println("Full service stopped")
	return nil
}

// GetMetrics 获取服务指标
func (fs *FullService) GetMetrics() *stats.Metrics {
	return fs.collector.GetMetrics()
}

// Helper: registry 下载器适配器

type registryDownloader struct {
	client *registry.Client
}

func (rd *registryDownloader) Download(ctx context.Context, path string, offset, size int64) ([]byte, error) {
	// 简化实现
	return nil, nil
}

// ---

// containerd config.toml 集成配置
/*
[plugins."io.containerd.snapshotter.v1.onyx"]
  root_path = "/var/lib/onyx-snapshotter"

  # 块配置
  chunk_size = 4194304  # 4MB

  # 数据库配置
  db_backend = "pebble"

  # 功能开关
  fanotify_enabled = true
  ublk_enabled = true

  # 去重配置
  dedup_rate = 0.75

  # 预取配置
  prefetch_enabled = true
  prefetch_threads = 4

[plugins."io.containerd.snapshotter.v1.onyx".metrics]
  enabled = true
  endpoint = "127.0.0.1:8080"
*/

// ---
